const app = getApp();
import { list, remove } from '../../../api/mine/like';
import Dialog from '../../../miniprogram_npm/@vant/weapp/dialog/dialog';

Page({
  data: {
    back: true,
    title: '我的收藏',
    loading: true,
    loadmore: false,
    init: true,
    list: null,
    form: {
      page: 1,
      limit: 10
    },
    abnor: {
      title: '您还没有收藏商品哦~',
      button: ''
    }
  },
  onLoad (options) {
    this.setData({ loading: true })
  },
  onShow () {
    this.init()
    this.getList()
  },
  onPullDownRefresh() {/*监听用户下拉动作*/ },
  onReachBottom() {
    if (this.data.form.page == this.data.form.last_page) {
      this.setData({ loadmore: true })
    } else {
      this.data.form.page += 1
      this.getList()
    }
  },

  //===================methon================

  getList() {
    list(this.data.form).then(res => {
      const { data } = res
      this.data.list || (this.data.list = [])
      const list = this.data.list.concat(data.data)
      this.data.form.last_page = res.data.last_page
      this.setData({
        list: list,
        init: false,
        loadmore: data.last_page <= 1
      })
    })
      .finally(() => {
        this.setData({ loading: false })
      })
  },

  remove(event) {
    if (event.detail == 'right') {
      const id = event.currentTarget.id;
      const that = this;
      let list = [];
      this.data.list.forEach(item => {
        if (item.id != id) {
          list.push(item);
        }
      });
      remove(id).then(res => {
        app.toast('删除成功', function () {
          that.setData({
            list: list
          });
        }, 'success');
      });
    }
  },

  init () {
    this.setData({
      list: null,
      loadmore: false,
      form: {
        page: 1,
        limit: 10
      }
    })
  },

  redirect(event) {
    app.redirect(event.currentTarget.dataset.url)
  },

  onAbnor() {
    app.redirect('/pages/goods/index/index');
  }
})